package com.kykj.kykj.config;

import com.kykj.kykj.service.impl.TokenServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
//urlPatterns:需要对哪些url进行过滤，例如：/user/* 就会对 /user/下面的所有URL进行过滤。*：通配所有
//filterName：过滤器名称

@WebFilter(urlPatterns = "/*",filterName = "WebXFilter")
public class WebXFilter extends HttpFilter {
    @Resource
    TokenServiceImpl tokenService;

    public void init(FilterConfig config) throws ServletException {
        System.out.println("创建过滤器");
    }

    public void destroy() {
        System.out.println("销毁过滤器");
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream servletOutputStream = response.getOutputStream();//输出对象
        try{
            if(request.getMethod().equals("OPTIONS")){ //预检，统统通过
                chain.doFilter(request,response);//继续向下（通过当前过滤器）
            }else{
                if (!request.getRequestURI().equals("/v2/user/dologin") &&
                        !request.getRequestURI().equals("/v2/user/user")){
                    // 验证 Token
                    String token = request.getHeader("token");
                    String uname = request.getHeader("uname");
                    if (tokenService.isToken(uname,token)){//符合的token
                        chain.doFilter(request,response);//继续向下（通过当前过滤器）
                    }else{
                        servletOutputStream.write("{\"code\":0,\"msg\":\"Token错误或者不存在！\"}".getBytes());
                    }
                }else{//登录接口（直接通过）
                    chain.doFilter(request,response);//继续向下（通过当前过滤器）
                }
            }

        }catch (Exception e){
            servletOutputStream.write("{\"code\":-1,\"msg\":\"未传入Token！\"}".getBytes());
        }
    }
}
